package com.gs.spring.util.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import com.gs.spring.core.domain.Patient;
import com.gs.spring.core.domain.Person;
import com.gs.spring.core.domain.Visit;
import com.gs.spring.core.service.PatientService;
import com.gs.spring.util.service.PatientUtilService;

@Service(value="patientUtilServiceStub")
public class PatientUtilServiceStub implements PatientUtilService, InitializingBean {
	
	static Map<Long, Patient> patients = new HashMap<Long, Patient>();
	
	public void initPatients(){
		
		Patient patient = null;
		for (int i = 0; i < 10; i++) {
			patient = getPatient();
			patient.setVisits(new ArrayList<Visit>());
			patients.put(patient.getId(), patient);
		}
	}
	
	private static Patient getPatient(){
		Patient patient = null;
		Person person =  null;
		String firstName = "First Name ";
		String lastName = "Last Name ";
		String code = "P-";
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int random = 0;
		int dayOfYr = 0;
		do{
			random = getRandom();
			if(random<100){
				break;
			}
			cal.setTime(new Date());
			dayOfYr = (random%1000);
			cal.set(Calendar.DAY_OF_YEAR, (-1)*dayOfYr);
		}while(true);
		person = new Person(firstName+dayOfYr,lastName+dayOfYr,cal.getTime());
		patient = new Patient(Long.valueOf(dayOfYr),person,code+dayOfYr);
		return patient;
	}

	private static int getRandom() {
		Random r = new Random();
		return r.nextInt();
	}
	
	public Collection<Patient> findAll(){
		return patients.values();
	}
	public Patient findOne(Long id){
		return patients.get(id);
	}

	public void afterPropertiesSet() throws Exception {
		initPatients();		
	}

	public Patient savePatient(Patient patient) {
		System.out.println("Saved patient in stub");
		return patient;
	}
}
